import {
  Component,
  OnInit,
  AfterViewInit,
  AfterContentInit,
  ViewChild,
  ElementRef,
  ViewChildren,
  QueryList,
  ContentChildren
} from '@angular/core';
import {ProductService} from '../../product/product.service';
import {Router, ActivatedRoute, ParamMap , NavigationEnd} from '@angular/router';
import 'rxjs/add/operator/switchMap';
import {NzModalService, NzMessageService} from 'ng-zorro-antd';
import {AdOssUploadService} from '../../../lib/service/ad-oss-upload.service';
import {LocalStorageService} from '../../../lib/service/local-storage.service';
import {
  FormBuilder,
  FormGroup,
  Validators,
  FormControl
} from '@angular/forms';
import {TemplateService} from '../template.service';
import {Observable} from 'rxjs/Observable';
import {isInteger} from '../../../../../node_modules/@ng-bootstrap/ng-bootstrap/util/util';

@Component({
  selector: 'app-product-page',
  templateUrl: './spec.component.html',
  styleUrls: ['./spec.component.scss'],
  providers: [TemplateService, ProductService, AdOssUploadService, LocalStorageService]
})

export class SpecComponent implements OnInit {
  validateForm: FormGroup;
  templateid: any;
  shopid: any;
  specList = [];
  specArr = [];
  specArr1 = [];
  idsArr = [];
  specIndex = 1;
  dataSave: any = {};
  addshow: boolean;
  typeOpen: boolean;
  typeValue: any;
  addModalVisible: boolean;

  constructor(public TemplateService: TemplateService,
              private route: ActivatedRoute,
              private _message: NzMessageService,
              private confirmServ: NzModalService,
              private router: Router,
              private localStorageService: LocalStorageService,
              private fb: FormBuilder) {
    this.router.events
      .filter((event) => event instanceof NavigationEnd)
      .subscribe((event: NavigationEnd ) => {
        this.shopid = this.localStorageService.getShop()['id'];
        // this.getGroupList();
      });
    this.validateForm = fb.group({
      name: ['', [Validators.required, Validators.maxLength(30)]],
      sort: ['', [Validators.required, Validators.min(0), Validators.max(99)], this.integerValidators],
    });

  }
  // 整数验证
  integerValidators = (control: FormControl) => {
    return Observable.create((observer) => {
      if (!isInteger(control.value)) {
        observer.next({ error: true, notInteger: true });
      } else {
        observer.next(null);
      }
      observer.complete();
    });
  }

  ngOnInit() {
      this.route.queryParams.subscribe(params => {
        console.log('--id', params.id);
        this.templateid = params.id;
      });

    // this.validateForm = this.fb.group({
    //   spec: [1],
    // });
  }

  addInput(e) {
    e.stopPropagation();
    // this.addshow = true;
    // this.typeOpen = true;
    this.addModalVisible = true;
  }
  addType(item?) {
    if (item == null) {
      item = {};
    }
    if (this.typeValue) {
      this.addTypeValue(item);
    } else {
      this.addshow = false;
    }
  }

    addTypeValue(item) {
      let data = {name: this.typeValue, sort: 0, shop_id: this.shopid, attribute_template_id: this.templateid} ;
      this.TemplateService.addSpecName(data).subscribe(res => {
        if (res.code === 200) {
          this.typeValue = '';
          this.addshow = false;
          // this.getGroupList();
          this._message.create('success', '分类添加成功');
        } else {
          this._message.create('error', res.message);
        }
  });
    }
  initspecList() {
    this.specList.forEach((item) => {
      this.validateForm.addControl('spec[' + item.index + ']', this.fb.control(item.title));

      item.list.forEach((item1) => {
        this.validateForm.addControl('spec[' + item.index + '][' + item1.index + ']', this.fb.control(item1.title));
      });
    });
  }

  goBack() {
    this.router.navigate([`member/template/list`],{
      queryParams: {
        // showcaseId: this.showcase_id
      }
    });
  }
  checkspecValue() {
    let validateForm = this.validateForm;
    let pd = false;
    let idsArr = this.idsArr;
    let specArr = this.specArr;
    for ( var i = 0, len = specArr.length; i < len; i++) {
      if ((validateForm.controls['[' + idsArr[i] + '][price]'].dirty &&
        validateForm.controls['[' + idsArr[i] + '][price]'].hasError('required')) ||
        (validateForm.controls['[' + idsArr[i] + '][retail_Price]'].dirty &&
          validateForm.controls['[' + idsArr[i] + '][retail_Price]'].hasError('required')) ||
        (validateForm.controls['[' + idsArr[i] + '][in_stock]'].dirty &&
          validateForm.controls['[' + idsArr[i] + '][in_stock]'].hasError('required'))
      ) {
        pd = true;
        break;
      }
    }
    return pd;
  }

  addspec(e) { // 添加规格
    e.preventDefault();
    let len = this.specIndex;
    this.validateForm.addControl('spec[' + len + ']', this.fb.control(''));
    this.validateForm.addControl('spec[' + len + '][0]', this.fb.control(''));
    this.specList.push({
      edit: true,
      title: '',
      index: len,
      childLen: 1,
      valuelen: 0,
      valueindex: 0,
      list: [
        {title: '', index: 0}
      ]
    });
    this.specIndex++;
  }

}
